package com.wenzhoujie;

import java.util.List;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.wenzhoujie.library.title.SDTitleSimple.SDTitleSimpleListener;
import com.wenzhoujie.library.utils.SDToast;
import com.wenzhoujie.library.utils.SDViewUtil;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lingou.www.R;
import com.sunday.eventbus.SDBaseEvent;
import com.wenzhoujie.app.App;
import com.wenzhoujie.app.AppHelper;
import com.wenzhoujie.constant.Constant.TitleType;
import com.wenzhoujie.event.EventTagJpush;
import com.wenzhoujie.fragment.EventDetailTopFragment;
import com.wenzhoujie.fragment.EvevtsDetailCommentFragment;
import com.wenzhoujie.fragment.EvevtsDetailWebViewFragment;
import com.wenzhoujie.http.InterfaceServer;
import com.wenzhoujie.model.EventdetailItemCommentsModel;
import com.wenzhoujie.model.EventdetailItemField_listModel;
import com.wenzhoujie.model.EventdetailItemModel;
import com.wenzhoujie.model.LocalUserModel;
import com.wenzhoujie.model.RequestModel;
import com.wenzhoujie.model.act.BaseActModel;
import com.wenzhoujie.model.act.EventdetailActModel;
import com.wenzhoujie.utils.IocUtil;
import com.wenzhoujie.utils.JsonUtil;
import com.wenzhoujie.utils.SDInterfaceUtil;
import com.wenzhoujie.utils.SDTypeParseUtil;
import com.wenzhoujie.utils.ViewInject;

/**
 * 活动详情
 * 
 * @author js02
 * 
 */
public class EventsDetailActivity extends BaseActivity implements OnClickListener
{
	/** events_id */
	public static final String EXTRA_EVENTS_ID = "EXTRA_EVENTS_ID";

	private static final String SELECT_BTN_STRING = "请选择范围";

	@ViewInject(id = R.id.act_events_detail_ptrsv_all)
	private PullToRefreshScrollView mPtrsvAll = null;

	@ViewInject(id = R.id.include_events_detail_ll_fieldlist)
	private LinearLayout mLlFieldlist = null;

	@ViewInject(id = R.id.include_events_detail_tv_apply_event)
	private TextView mTvApplyEvent = null;

	@ViewInject(id = R.id.include_events_detail_tv_comment_event)
	private TextView mTvCommentEvent = null;

	private EventdetailItemModel mDetailItemModel = null;

	private EventDetailTopFragment mFragTop = null;
	private EvevtsDetailWebViewFragment mFragWebView = null;
	private EvevtsDetailCommentFragment mFragComment = null;

	private int page;
	private int pageTotal;

	private String events_id = null;
	private int is_bm = 0;
	private List<String> mListFieldScopeValue;

	private JSONObject mUserInfo = new JSONObject();

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		mIsNeedSlideFinishLayout = false;
		super.onCreate(savedInstanceState);
		setmTitleType(TitleType.TITLE_SIMPLE);
		setContentView(R.layout.act_events_detail);
		IocUtil.initInjectedView(this);
		init();
	}

	private void init()
	{
		getIntentData();
		initTitle();
		registeClick();
		initPullToRefreshScrollView();
	}

	private void initPullToRefreshScrollView()
	{
		mPtrsvAll.setMode(Mode.BOTH);
		mPtrsvAll.setOnRefreshListener(new OnRefreshListener2<ScrollView>()
		{
			@Override
			public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView)
			{
				page = 1;
				is_bm = 0;
				requestEventsDetail(false);
			}

			@Override
			public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView)
			{
				if (++page > pageTotal && pageTotal > 0)
				{
					SDToast.showToast("没有更多评论了");
					mPtrsvAll.onRefreshComplete();
				} else
				{
					requestEventsDetail(true);
				}
			}
		});
		mPtrsvAll.setRefreshing();
	}

	private void getIntentData()
	{
		Intent intent = getIntent();
		events_id = intent.getStringExtra(EXTRA_EVENTS_ID);
	}

	@Override
	protected void onNewIntent(Intent intent)
	{
		setIntent(intent);
		init();
		super.onNewIntent(intent);
	}

	private void initTitle()
	{
		mTitleSimple.setmListener(new SDTitleSimpleListener()
		{

			@Override
			public void onRightButtonCLick_SDTitleSimple(View v)
			{
			}

			@Override
			public void onLeftButtonCLick_SDTitleSimple(View v)
			{
				finish();
			}
		});
		mTitleSimple.setTitleTop("活动");
	}

	private void registeClick()
	{
		mTvApplyEvent.setOnClickListener(this);
		mTvCommentEvent.setOnClickListener(this);
	}

	@Override
	public void onClick(View v)
	{
		switch (v.getId())
		{
		case R.id.include_events_detail_tv_apply_event:

			clickApplyEvent();

			break;
		case R.id.include_events_detail_tv_comment_event:

			clickCommentEvent();

			break;
		default:
			break;
		}
	}

	/**
	 * 评论按钮
	 */
	private void clickCommentEvent()
	{
		if (AppHelper.isLogin())
		{
			Dialog dialog = new MyDialog(EventsDetailActivity.this, R.style.MyDialog);
			// 设置触摸对话框以外的地方取消对话框
			dialog.setCanceledOnTouchOutside(true);
			dialog.show();
		} else
		{
			SDToast.showToast("请先登录");
			Intent intent = new Intent();
			intent.setClass(EventsDetailActivity.this, LoginNewActivity.class);
			startActivity(intent);
		}
	}

	/**
	 * 报名按钮
	 */
	private void clickApplyEvent()
	{
		if (!AppHelper.isLogin())
		{
			startActivity(new Intent(getApplicationContext(), LoginNewActivity.class));
			return;
		}

		if (fillUserInfo())
		{
			is_bm = 1;
			requestEventsDetail(false);
		}
	}

	/**
	 * 填充用户填写的资料到jsonObject中
	 */
	private boolean fillUserInfo()
	{
		if (mDetailItemModel != null)
		{
			List<EventdetailItemField_listModel> listField = mDetailItemModel.getField_list();
			if (listField != null && listField.size() > 0)
			{
				for (EventdetailItemField_listModel fieldModel : listField)
				{
					if (fieldModel != null)
					{
						View view = fieldModel.getView();
						if (view != null)
						{
							try
							{
								if (view instanceof Button) // 如果是button
								{
									Button btnScope = (Button) view;
									String strScope = btnScope.getText().toString();
									if (SELECT_BTN_STRING.equals(strScope))
									{
										SDToast.showToast("请选择" + fieldModel.getField_show_name());
										return false;
									} else
									{
										mUserInfo.put(String.valueOf(fieldModel.getId()), strScope);
									}
								} else if (view instanceof EditText) // 如果是edittext
								{
									EditText etInfo = (EditText) view;
									String strInfo = etInfo.getText().toString();
									if (AppHelper.isEmptyString(strInfo))
									{
										SDToast.showToast("请输入" + fieldModel.getField_show_name());
										return false;
									} else
									{
										mUserInfo.put(String.valueOf(fieldModel.getId()), strInfo);
									}
								}
							} catch (Exception e)
							{
								return false;
							}
						}
					}
				}
				return true;
			}
		}
		return true;
	}

	/**
	 * 请求活动详情接口
	 */
	private void requestEventsDetail(final boolean isLoadMore)
	{
		LocalUserModel user = App.getApplication().getmLocalUser();
		if (!TextUtils.isEmpty(events_id))
		{
			RequestModel model = new RequestModel();
			model.put("act", "eventdetail");
			model.put("event_id", events_id);
			if (user != null)
			{
				model.put("email", user.getUser_name());
				model.put("pwd", user.getUser_pwd());
			}
			model.put("source", "Android客户端");
			model.put("page", page);
			if (is_bm == 1)
			{
				model.put("act_2", "bm");
				model.put("bm", mUserInfo);
			}
			RequestCallBack<String> handler = new RequestCallBack<String>()
			{

				@Override
				public void onStart()
				{
					AppHelper.showLoadingDialog("请稍候...");
				}

				@Override
				public void onSuccess(ResponseInfo<String> responseInfo)
				{
					EventdetailActModel actModel = JsonUtil.json2Object(responseInfo.result, EventdetailActModel.class);
					if (!SDInterfaceUtil.isActModelNull(actModel))
					{
						if (actModel.getResponse_code() == 1)
						{
							if (actModel.getPage() != null)
							{
								page = actModel.getPage().getPage();
								pageTotal = actModel.getPage().getPage_total();
							}
							mDetailItemModel = actModel.getItem();
							addFragments(actModel.getItem(), isLoadMore);
							initFieldList(actModel.getItem());
							
						
						}
						if (is_bm == 1)
						{
							is_bm = 0;
							requestEventsDetail(false);
						}
					}
				}

				@Override
				public void onFailure(HttpException error, String msg)
				{

				}

				@Override
				public void onFinish()
				{
					AppHelper.hideLoadingDialog();
					mPtrsvAll.onRefreshComplete();
				}
			};
			InterfaceServer.getInstance().requestInterface(model, handler);
		}
	}

	/**
	 * 发表评论接口
	 */
	private void requestComment(String content)
	{
		LocalUserModel user = App.getApplication().getmLocalUser();
		if (!TextUtils.isEmpty(events_id))
		{
			RequestModel model = new RequestModel();
			model.put("act", "addeventcomment");
			model.put("event_id", events_id);
			if (user != null)
			{
				model.put("email", user.getUser_name());
				model.put("pwd", user.getUser_pwd());
			}
			model.put("content", content);
			RequestCallBack<String> handler = new RequestCallBack<String>()
			{

				@Override
				public void onStart()
				{
					AppHelper.showLoadingDialog("请稍候...");
				}

				@Override
				public void onSuccess(ResponseInfo<String> responseInfo)
				{
					BaseActModel actModel = JsonUtil.json2Object(responseInfo.result, BaseActModel.class);
					if (!SDInterfaceUtil.isActModelNull(actModel))
					{
						int status = SDTypeParseUtil.getIntFromString(actModel.getStatus(), 0);
						if (status == 1)
						{
							requestEventsDetail(false);
						}
					}
				}

				@Override
				public void onFailure(HttpException error, String msg)
				{

				}

				@Override
				public void onFinish()
				{
					AppHelper.hideLoadingDialog();
				}
			};
			InterfaceServer.getInstance().requestInterface(model, handler);
		}
	}

	/**
	 * 添加fragment
	 */
	private void addFragments(EventdetailItemModel detailItemModel, boolean isLoadMore)
	{
		if (detailItemModel == null)
		{
			return;
		}

		if (!isLoadMore)
		{
			mFragTop = new EventDetailTopFragment();
			mFragTop.setEventsModel(detailItemModel);
			addFragment(mFragTop, R.id.act_events_detail_fl_container_top);

			mFragWebView = new EvevtsDetailWebViewFragment();
			mFragWebView.setEventsModel(detailItemModel);
			addFragment(mFragWebView, R.id.act_events_detail_fl_container_first);
		} else
		{
			if (mFragComment != null)
			{
				EventdetailItemModel oldModel = mFragComment.getEventsModel();
				if (oldModel != null)
				{
					List<EventdetailItemCommentsModel> listOldComment = oldModel.getComments();
					if (listOldComment != null)
					{
						List<EventdetailItemCommentsModel> listNewComment = detailItemModel.getComments();
						if (listNewComment != null)
						{
							listOldComment.addAll(listNewComment);
							detailItemModel.setComments(listOldComment);
						}
					}
				}
			}
		}

		mFragComment = new EvevtsDetailCommentFragment();
		mFragComment.setEventsModel(detailItemModel);
		addFragment(mFragComment, R.id.act_events_detail_fl_container_second);

	}

	/**
	 * 填充FieldList
	 */
	private void initFieldList(EventdetailItemModel detailItemModel)
	{
		if (detailItemModel == null)
		{
			return;
		}

		List<EventdetailItemField_listModel> listDetailItemFieldModel = detailItemModel.getField_list();
		if (detailItemModel.getIs_submit() == 1)
		{
			mLlFieldlist.setVisibility(View.GONE);
			mTvApplyEvent.setText("已报名 ("+mDetailItemModel.getSubmit_count()+")");
			mTvApplyEvent.setEnabled(false);
		} else
		{
			mLlFieldlist.setVisibility(View.VISIBLE);
			mTvApplyEvent.setText("马上报名 ("+mDetailItemModel.getSubmit_count()+")");
			mTvApplyEvent.setEnabled(true);

			mLlFieldlist.removeAllViews();
			EventdetailItemField_listModel fieldModel = null;
			for (int i = 0; i < listDetailItemFieldModel.size(); i++)
			{
				fieldModel = listDetailItemFieldModel.get(i);
				if (fieldModel == null)
				{
					continue;
				}

				LinearLayout llItem = new LinearLayout(EventsDetailActivity.this);
				llItem.setOrientation(LinearLayout.HORIZONTAL);
				llItem.setGravity(Gravity.CENTER_VERTICAL);

				TextView tvLabel = new TextView(EventsDetailActivity.this);
				tvLabel.setText(fieldModel.getField_show_name() + ":　");
				tvLabel.setTextSize(15);
				tvLabel.setTextColor(Color.BLACK);
				tvLabel.setGravity(Gravity.CENTER);

				if (fieldModel.getField_type() == 0) // edittext
				{
					EditText etInfo = new EditText(EventsDetailActivity.this);
					fieldModel.setView(etInfo);
					etInfo.setPadding(SDViewUtil.dp2px(5), 0, 0, 0);
					etInfo.setSingleLine(true);
					etInfo.setTextColor(getResources().getColor(R.color.black));
					etInfo.setBackgroundResource(R.drawable.layer_white_stroke_item_single);
					llItem.addView(tvLabel, new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
					llItem.addView(etInfo, new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, SDViewUtil.dp2px(40)));
				} else if (fieldModel.getField_type() == 1)// button
				{
					final Button btnScope = new Button(EventsDetailActivity.this);
					fieldModel.setView(btnScope);
					btnScope.setText("请选择范围");
					btnScope.setTextColor(getResources().getColor(R.color.white));
					btnScope.setBackgroundResource(R.drawable.selector_main_color);
					btnScope.setTag(fieldModel);
					btnScope.setOnClickListener(new OnClickListener()
					{

						@Override
						public void onClick(View v)
						{
							final EventdetailItemField_listModel list = (EventdetailItemField_listModel) v.getTag();
							mListFieldScopeValue = list.getValue_scope();
							Builder builder = new AlertDialog.Builder(EventsDetailActivity.this);
							builder.setAdapter(new MyValueAdapter(), new DialogInterface.OnClickListener()
							{

								@Override
								public void onClick(DialogInterface dialog, int which)
								{
									btnScope.setText(mListFieldScopeValue.get(which));
								}
							});
							builder.create().show();
						}
					});
					llItem.addView(tvLabel, new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
					llItem.addView(btnScope, new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
				}

				LinearLayout.LayoutParams paramsItem = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
				paramsItem.bottomMargin = SDViewUtil.dp2px(5);
				paramsItem.topMargin = SDViewUtil.dp2px(5);
				mLlFieldlist.addView(llItem, paramsItem);
			}
			mLlFieldlist.setVisibility(View.VISIBLE);
		}

	}

	/**
	 * 简单适配器
	 */
	private class MyValueAdapter extends BaseAdapter
	{

		@Override
		public int getCount()
		{
			return mListFieldScopeValue.size();
		}

		@Override
		public Object getItem(int position)
		{
			return mListFieldScopeValue.get(position);
		}

		@Override
		public long getItemId(int position)
		{
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent)
		{

			TextView tv = new TextView(EventsDetailActivity.this);
			tv.setText(mListFieldScopeValue.get(position));
			tv.setPadding(0, 20, 0, 20);
			tv.setBackgroundColor(getResources().getColor(R.color.white));
			tv.setTextSize(22);
			tv.setGravity(Gravity.CENTER);
			tv.setTextColor(Color.BLACK);
			return tv;
		}

	}

	/**
	 * 自定义对话框的类
	 */
	class MyDialog extends Dialog
	{

		public MyDialog(Context context, int theme)
		{
			super(context, theme);
		}

		@Override
		protected void onCreate(Bundle savedInstanceState)
		{
			super.onCreate(savedInstanceState);
			this.setContentView(R.layout.dialog);
			// 退出按钮和返回按钮
			Button submit_button, return_button;
			final EditText content_text;
			// 初始化
			submit_button = (Button) findViewById(R.id.submit_button);
			return_button = (Button) findViewById(R.id.return_button);
			content_text = (EditText) findViewById(R.id.dlg_input_content);

			// 发表
			submit_button.setOnClickListener(new View.OnClickListener()
			{

				@Override
				public void onClick(View v)
				{
					if (AppHelper.isEmptyString(content_text.getText().toString()))
					{
						SDToast.showToast("点评内容为空,发布失败!");
					} else
					{
						requestComment(content_text.getText().toString());
						dismiss();
					}
				}
			});

			// 返回
			return_button.setOnClickListener(new View.OnClickListener()
			{
				@Override
				public void onClick(View v)
				{
					// 关闭对话框
					dismiss();
				}
			});
		}

	}

	@Override
	public void onEventMainThread(SDBaseEvent event)
	{
		// TODO Auto-generated method stub
		super.onEventMainThread(event);
		if (EventTagJpush.EVENT_EVENTSDETAIL_ID.equals(event.getEventTagString()))
		{
			finish();
		}
	}
}